import React from 'react'
import ReactDOM from 'reactDom'
import BasePageView from 'BasePageView'
import SiteMap from 'SiteMap'

const Config = {
  PageIdentity: SiteMap.DemandSheet,
}

const Transformer = {
  Number,
  String,
  Boolean,
}

const Event = {
  events: {
    'click .js_increment': 'handleIncrement',
    'change [name]': 'handleInputChange',
    'blur [name]': 'handleInputChange',
  },
  handleIncrement: function(event) {
    this.setState({
      form: {
        ...this.state.form,
        count: this.state.form.count + 1
      }
    })
  },
  handleInputChange: function(event) {
    const { currentTarget } = event
    const path = currentTarget.getAttribute('name')
    const dataType = currentTarget.getAttribute('data-type')
    let currentValue = currentTarget.value
    if (dataType) {
      if (this[dataType]) {
        currentValue = this[dataType](currentValue)
      }
    }
    const newState = setValueByPath(this.state, path, currentValue)
    this.setState(newState)
  }
}

const Base = {
  // 初始化调用，在生命周期中只调用一次
  onCreate: function() {
    window.view = this
    this.getInitialState()
    this.render()
  },
  // 显示时调用
  onShow: function() {},
  // 隐藏时调用
  onHide: function() {
    delete window.view
  },
  // 获得视口时调用，此方法仅在`hybrid`有效
  onAppear: function() {},

  getInitialState: function() {
    this.state = {
      form: {
        count: 0,
      },
      username: 'safarishi'
    }
  },

  render: function() {
    const container = this.$el[0]
    ReactDOM.render(
      <Provider controller={this}>
        <View state={this.state} />
      </Provider>,
      container
    )
  },

  setState: function(newState) {
    this.state = {
      ...this.state,
      ...newState
    }
    this.render()
  }
}

function View({ state }) {
  return (
    <div>
      <Input className='xxx' name='form.count' data-type='Number' value={state.form.count} />
      <Input className='bbb' name='username' value={state.username} />
      <button className='js_increment'>+1</button>
      <p>TheCurrentValue: {state.form.count}</p>
      <pre>{JSON.stringify(state, null, 2)}</pre>
    </div>
  )
}

class Provider extends React.PureComponent {
  static childContextTypes = {
    controller: React.PropTypes.object,
  }
  getChildContext() {
    return {
      controller: this.props.controller
    }
  }
  render() {
    return React.Children.only(this.props.children)
  }
}

class Input extends React.PureComponent {
  static contextTypes = {
    controller: React.PropTypes.object
  }
  render() {
    return <input {...this.props} onChange={this.handleChange} />
  }
  handleChange = event => {
    const { controller } = this.context
    if (controller.handleInputChange) {
      controller.handleInputChange(event)
    }
  }
}

function getValueByPath(obj, path) {
  path = !Array.isArray(path) ? path.split('.') : path
  return path.reduce((ret, key) => ret[key], obj)
}

function setValueByPath(obj, path, value) {
  path = !Array.isArray(path) ? path.split('.') : path
  let list = path.reduce(
    (list, key, index) => {
      if (index === path.length - 1) {
        list[index][key] = value
      } else {
        let target = list[index][key]
        if (Array.isArray(target)) {
          target = target.concat()
        } else {
          target = { ...target }
        }
        list[index][key] = target
        list.push(target)
      }
      return list
    },
    [{ ...obj }]
  )

  return list[0]
}

export default BasePageView.extend($.extend(true, Base, Config, Transformer, Event))